import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import ProjectList from '../views/ProjectList.vue'
import ProjectDetail from '../views/ProjectDetail.vue'
import ProjectCreate from '../views/ProjectCreate.vue'
import EndpointMonitor from '../views/EndpointMonitor.vue'
import AddEndpoint from '../views/AddEndpoint.vue'
import NotFound from '../views/NotFound.vue'
import Login from '../views/Login.vue'

console.log('路由模块开始加载 at:', new Date().toISOString())

const routes = [
  {
    path: '/',
    name: 'ProjectList',
    component: ProjectList,
    meta: {
      requiresAuth: true,
      title: '项目管理'
    }
  },
  {
    path: '/project/create',
    name: 'ProjectCreate',
    component: ProjectCreate,
    meta: {
      requiresAuth: true,
      title: '创建项目'
    }
  },
  {
    path: '/project/:id/edit',
    name: 'ProjectEdit',
    component: ProjectCreate,
    props: true,
    meta: {
      requiresAuth: true,
      title: '编辑项目'
    }
  },
  {
    path: '/project/:id',
    name: 'ProjectDetail',
    component: ProjectDetail,
    props: true,
    meta: {
      requiresAuth: true,
      title: '项目详情'
    }
  },
  {
    path: '/project/:projectId/endpoints/add',
    name: 'AddEndpoint',
    component: AddEndpoint,
    props: true,
    meta: {
      requiresAuth: true,
      title: '添加接口'
    }
  },
  {
    path: '/project/:projectId/endpoints/edit/:endpointId',
    name: 'EditEndpoint',
    component: AddEndpoint,
    props: true,
    meta: {
      requiresAuth: true,
      title: '编辑接口'
    }
  },
  {
    path: '/project/:projectId/endpoints',
    name: 'EndpointMonitor',
    component: EndpointMonitor,
    props: true,
    meta: {
      requiresAuth: true,
      title: '接口监控'
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录',
      guestOnly: true
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: NotFound,
    meta: {
      title: '页面未找到'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

console.log('路由配置完成 at:', new Date().toISOString())

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

console.log('路由实例创建完成 at:', new Date().toISOString())

// 全局前置守卫
router.beforeEach((to, from, next) => {
  console.log('路由守卫开始 at:', new Date().toISOString(), '从', from.path, '到', to.path)
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - API Pulse`
  }

  const token = localStorage.getItem('token')

  // 检查是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      console.log('用户未登录，重定向到登录页 at:', new Date().toISOString())
      ElMessage.warning('请先登录')
      next({ path: '/login', query: { redirect: to.fullPath } })
      return
    }
  }

  // 检查是否仅允许未登录用户访问（如登录页面）
  if (to.matched.some(record => record.meta.guestOnly)) {
    if (token) {
      console.log('用户已登录，重定向到首页 at:', new Date().toISOString())
      ElMessage.warning('您已登录')
      next('/')
      return
    }
  }

  console.log('路由守卫结束，允许访问 at:', new Date().toISOString())
  next()
})

// 全局后置钩子
router.afterEach((to, from) => {
  console.log('路由切换完成 at:', new Date().toISOString(), '从', from.path, '到', to.path)
})

console.log('路由模块加载完成 at:', new Date().toISOString())

export default router